//
//  AddMiddleManViewController2.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/4/20.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "AddMiddleManViewController2.h"
#import "BdTV.h"
#import "config.h"
#import "LoginDataMange.h"
#import "MBProgressHUD+MJ.h"
#import "StringTool.h"
#import "AddBrokerModel.h"
#import "BrokerDM.h"

#import "UserModal.h"
#import "UIView+circular.h"

@interface AddMiddleManViewController2 ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIButton *companyBtn;
@property (weak, nonatomic) IBOutlet UITextField *nameEt;
@property (weak, nonatomic) IBOutlet UITextField *mobileEt;
@property (weak, nonatomic) IBOutlet UITextField *codeEt;
@property (weak, nonatomic) IBOutlet UITextField *codeAgainEt;


@property (weak, nonatomic) IBOutlet UIButton *getYzBtn;
@property (weak, nonatomic) IBOutlet UITextField *yanZhenMaEt;
@property (nonatomic,copy) AddMiddleManVC returnBlock;
@property (nonatomic,strong)LoginDataMange *loginDM;
@property (nonatomic,strong)AddBrokerModel *model;

@property (nonatomic,strong)BrokerDM *dataMange;

@property (weak, nonatomic) IBOutlet UIButton *saveBtn;


@end

@implementation AddMiddleManViewController2
@synthesize loginDM,model,dataMange;

-(instancetype)initWithBlock:(AddMiddleManVC)block
{
    if (self = [super init]) {
       
        self.returnBlock = block;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
}


-(void)initView
{
    [super initView];
    
    [self.saveBtn viewToCircular];
    BdTV *title = [[BdTV alloc]initWithFrame:CGRectMake(0, 0, PMW, 44)];
    [title.backBtn setTag:11];
    [title.backBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [[title doneBtn] removeFromSuperview];
    [title setMianTitle:@"添加经纪人"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:title];
    
    
    
    self.companyBtn.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.companyBtn.layer.borderWidth= 1;
    self.companyBtn.layer.cornerRadius = 6;
    [self.companyBtn setTitle:self.storeModel.storeName forState:UIControlStateNormal];
    self.companyBtn.enabled = NO;
    [self.companyBtn.layer setMasksToBounds:true];
    
    self.getYzBtn.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.getYzBtn.layer.borderWidth= 1;
    self.getYzBtn.layer.cornerRadius = 6;
    self.getYzBtn.tag = 12;
    [self.getYzBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [self.getYzBtn.layer setMasksToBounds:true];
    
    self.nameEt.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.nameEt.layer.borderWidth= 1;
    self.nameEt.layer.cornerRadius = 6;
    self.nameEt.delegate = self;
    
    
    self.mobileEt.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.mobileEt.layer.borderWidth= 1;
    self.mobileEt.layer.cornerRadius = 6;
    self.mobileEt.delegate = self;
    
    self.yanZhenMaEt.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.yanZhenMaEt.layer.borderWidth= 1;
    self.yanZhenMaEt.layer.cornerRadius = 6;
    self.yanZhenMaEt.delegate = self;
    
    self.codeEt.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.codeEt.layer.borderWidth= 1;
    self.codeEt.layer.cornerRadius = 6;
    self.codeEt.delegate = self;
    
    self.codeAgainEt.layer.borderColor = UIColorFromRGB(0xe3e3e3).CGColor;
    self.codeAgainEt.layer.borderWidth= 1;
    self.codeAgainEt.layer.cornerRadius = 6;
    self.codeAgainEt.delegate =self;
    
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 1)];
        [self.nameEt setLeftViewMode:UITextFieldViewModeAlways];
        [self.nameEt setLeftView:leftView];
    }
    
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 1)];
        [self.mobileEt setLeftViewMode:UITextFieldViewModeAlways];
        [self.mobileEt setLeftView:leftView];
    }
    
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 1)];
        [self.codeEt setLeftViewMode:UITextFieldViewModeAlways];
        [self.codeEt setLeftView:leftView];
    }
    
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 1)];
        [self.codeAgainEt setLeftViewMode:UITextFieldViewModeAlways];
        [self.codeAgainEt setLeftView:leftView];
    }
    {
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 1)];
        [self.yanZhenMaEt setLeftViewMode:UITextFieldViewModeAlways];
        [self.yanZhenMaEt setLeftView:leftView];
        
    }

    loginDM = [[LoginDataMange alloc]init];
    dataMange = [[BrokerDM alloc]init];
}

-(void)btnOnclick:(UIButton *)btn
{
    if (btn.tag == 11) {//返回
        [self.navigationController popViewControllerAnimated:YES];
    }else if (btn.tag == 12)//获取验证码
    {
        if ([self checkPhone]) {
            [self getYanzhen];
        }
    }
}

#pragma mark 检查输入不为空
-(BOOL)checkInfo
{
    if ([StringTool isBlankString:self.nameEt.text] ) {
        [MBProgressHUD showError:@"请输入经纪人姓名"];
        return NO;
    }else if (![self checkPhone])
    {
        return NO;
    }else if ([StringTool isBlankString:self.yanZhenMaEt.text])
    {
        [MBProgressHUD showError:@"请输入验证码"];
        return NO;
    }else if (![self checkPwd])
    {
        return NO;
    }
    
    model = [[AddBrokerModel alloc]init];
    model.name = self.nameEt.text;
    model.password = self.codeEt.text;
    model.repassword = self.codeAgainEt.text;
    model.mobile = self.mobileEt.text;
    model.parentCode = self.storeModel.storeCode;
    model.captha = self.yanZhenMaEt.text;
   
    return YES;
}

#pragma mark 检查密码，和确认密码
-(BOOL)checkPwd
{
    if ([StringTool isBlankString:self.codeEt.text]) {
        [MBProgressHUD showError:@"请输入密码"];
        return NO;
    }else if ([StringTool isBlankString:self.codeAgainEt.text])
    {
        [MBProgressHUD showError:@"请输入确认密码"];
        return NO;
    }else if (![self.codeAgainEt.text isEqualToString:self.codeEt.text])
    {
        [MBProgressHUD showError:@"两次密码输入不一致"];
        return NO;
    }
    return YES;
}
#pragma mark 校验手机号
-(BOOL)checkPhone
{
    if ([StringTool isBlankString:self.mobileEt.text]) {
        [MBProgressHUD showError:@"请输入手机号"];
        return NO;
    }else
    {
        if (![self validateMobile:self.mobileEt.text]) {
            [MBProgressHUD showError:@"请输入正确的手机号"];
            return NO;
        }
    }
    return YES;
}
#pragma mark 获取验证码
-(void)getYanzhen
{
    [self Countdown];
    __weak typeof(self)bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        ResulteMod *mod = [loginDM captchaWithMobile:bself.mobileEt.text];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (mod.resltState == ResultFail) {
                [MBProgressHUD showError:mod.resultTip];
            }else if (mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络错误"];
            }else
            {
                [MBProgressHUD showSuccess:@"验证码已发送，注意查收"];
            }
        });
    });
}
#pragma mark 保存信息
- (IBAction)clickSaveInfoBtn:(id)sender
{
    if ([self checkInfo]) {
        [MBProgressHUD showMessage:@"请稍等" toView:self.view];
        
        __weak typeof(self)bself= self;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            ResulteMod *mod = [dataMange createbrokerWithAddBrokerModel:model];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD hideHUDForView:bself.view animated:YES];
                [bself.navigationController popViewControllerAnimated:YES];
                bself.returnBlock(mod.resltState);
                
                if (mod.resltState == ResultFail) {
                    [MBProgressHUD showError:mod.resultTip];
                }else if (mod.resltState == ResultNetError)
                {
                    [MBProgressHUD showError:@"网络错误"];
                }else
                {
                    [MBProgressHUD showSuccess:@"添加成功"];
                }
                
            });
        });

    }
 }



- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    
    CGRect dd =  textField.frame;
    
    int tvbotY = dd.size.height+dd.origin.y;
    int mid  = PMH-[UserModal shareUserModel].keyboardHeight-tvbotY;
    
    if (mid<0) {
        
        const float movementDuration = 0.3f;
        [UIView beginAnimations: nil context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        
        CGRect buf = self.view.frame;
        buf.origin.y = up ? mid : 0;
        [self.view setFrame:buf];
        
        [UIView commitAnimations];
    }else if(up==false){
        
        [self viewRest];
    }
}



-(void)viewRest{
    
    
    const float movementDuration = 0.3f;
    [UIView beginAnimations: nil context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    
    CGRect buf = self.view.frame;
    buf.origin.y =  64;
    [self.view setFrame:buf];
    
    [UIView commitAnimations];
}

#pragma et delegare
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    
    [textField resignFirstResponder];
    
    [self viewRest];
    return  YES;
}

#pragma mark 验证码倒计时
-(void)Countdown
{
    __block NSInteger timeout = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (timeout <=0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.getYzBtn setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
                self.getYzBtn.enabled = YES;
            });
            
        }else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.getYzBtn setTitle:[NSString stringWithFormat:@"%zd重新获取",timeout] forState:UIControlStateNormal];
                self.getYzBtn.enabled = NO;
                
            });
            timeout--;
        }
    });
    dispatch_resume(timer);
}

@end
